package org.tulkas.selector.pattern;

import java.util.Collection;
import java.util.TreeSet;

import org.tulkas.selector.Filter;
import org.tulkas.selector.FilterComparator;
import org.w3c.dom.Element;

/**
 * @author <a href="mailto:tulkas.web@gmail.com">Tulkas</a>
 *
 */
public class Chain implements Filter {
	private TreeSet<Filter> filters = new TreeSet<Filter>(
			new FilterComparator());

	public Chain(Collection<Filter> filters) {
		if (filters == null || filters.size() == 0) {
			throw new IllegalArgumentException(
					"A chain must contain at least 1 filter");
		}
		this.filters.addAll(filters);
	}

	/* (non-Javadoc)
	 * @see org.tulkas.selector.Filter#getPriority()
	 */
	@Override
	public int getPriority() {
		return filters.iterator().next().getPriority();
	}

	/* (non-Javadoc)
	 * @see org.tulkas.selector.Filter#matches(org.w3c.dom.Element)
	 */
	@Override
	public boolean matches(Element element) {
		for (Filter filter : filters) {
			if (!filter.matches(element)) {
				return false;
			}
		}
		return true;
	}

	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		;
		int i = 0;
		for (Filter filter : filters) {
			if (i > 0) {
				sb.append(" & ");
			}
			sb.append("(").append(filter.toString()).append(")");
		}
		return sb.toString();
	}

}
